﻿using Microsoft.EntityFrameworkCore;
using MiniFox.Data.EntityFramework;
using MiniFox.Infrastructure;
using Repository.Core.Models.Dto;
using Repository.Core.Models.Queries;
using Repository.Core.Models.VO;
using Repository.Core.Providers;
using Repository.Data.Entities.MySql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Repository.Data
{
    public class RepositoryProvider : EntityDataProvider<RepositoryContext>, IRepositoryProvider
    {
        public ResultObject<IEnumerable<RepositorySetVo>> Query(PagedQueryObject<CommonQuery> request)
        {
            var result = this.PagedQueryExecute<RepositorySet>(request);
            return result.GetResultObject(r => new RepositorySetVo
            {
                Name = r.Name,
                Description = r.Description,
                UpdateTime = r.UpdateTime,
                ItemCount = this.CurrentDbContext.VersionSet.Count(v => v.RepoName == r.Name),
            });
        }

        public RepositorySetVo GetItem(string name)
        {
            var item = this.CurrentDbContext.RepositorySet.SingleOrDefault(r => r.Name == name);
            if (item == null) return null;
            return new RepositorySetVo
            {
                Name = item.Name,
                Description = item.Description,
                UpdateTime = item.UpdateTime,
                ItemCount = this.CurrentDbContext.VersionSet.Count(v => v.RepoName == item.Name),
            };
        }

        public bool Save(RepositorySetDto dto)
        {
            var item = this.CurrentDbContext.RepositorySet.SingleOrDefault(r => r.Name == dto.Name);
            var newItem = (item == null);

            if (newItem)
            {
                item = new RepositorySet()
                {
                    Name = dto.Name,
                    Description = dto.Description,
                    UpdateTime = DateTime.Now
                };

                return this.Insert(item) > 0;
            }
            else
            {
                item.Description = dto.Description;
                item.UpdateTime = DateTime.Now;
                return this.Update(item) > 0;
            }
            
        }
    }
}
